<template>
    <div class="app-container enrollPage">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="姓名" prop="studentName">
          <el-input
            v-model="queryParams.studentName"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="系部" prop="deptId">
          <el-select v-model="queryParams.deptId" placeholder="请选择系部" clearable>
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="majorId">
          <el-select v-model="queryParams.majorId" placeholder="请选择专业" clearable>
            <el-option
              v-for="item in majorList"
              :key="item.id"
              :label="item.majorName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="招生年份" prop="zsYear">
          <el-date-picker v-model="queryParams.zsYear" value-format="yyyy"  type="year" placeholder="选择年" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:enroll:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:enroll:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:enroll:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['system:enroll:import']"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:enroll:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="准考证号" align="center" prop="candidateNumber" />
        <el-table-column label="学号" align="center" prop="sno" />
        <el-table-column label="姓名" align="center" prop="studentName" :show-overflow-tooltip="true" />
        <el-table-column label="系部" align="center" prop="deptName" />
        <el-table-column label="专业" align="center" prop="majorName" />
        <el-table-column label="学生类型" align="center" prop="studentType"  :formatter="formatInnerStudentTypeName"/>
        <el-table-column label="招生状态" align="center" prop="zsStatus"  :formatter="formatInnerZsStatus" width="150"/>
        <el-table-column label="招生年份" align="center" prop="zsYear"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:enroll:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:enroll:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-setting"
              @click="handleUpdate(scope.row,1)"
              v-hasPermi="['system:enroll:setting']" 
              v-if="scope.row.zsStatus == 6 || scope.row.zsStatus == 7"
            >分配班级</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
      <!-- 添加或修改定时学生信息对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="准考证号" prop="candidateNumber">
                <el-input v-model="form.candidateNumber" placeholder="请输入准考证号" type="number" :disabled="title == '分配班级'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="!!form.id">
              <el-form-item label="学号" prop="candidateNumber">
                <el-input :value="form.sno" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="studentName">
                <el-input v-model="form.studentName" placeholder="请输入姓名" :disabled="title == '分配班级'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="form.idCard" placeholder="请输入身份证号" :disabled="title == '分配班级'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="系部" prop="deptId">
                <el-select v-model="form.deptId" placeholder="请选择系部" :disabled="title == '分配班级'">
                  <el-option
                    v-for="item in deptList"
                    :key="item.deptId"
                    :label="item.deptName"
                    :value="item.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" prop="majorId">
                <el-select v-model="form.majorId" placeholder="请选择专业" :disabled="title == '分配班级'">
                  <el-option
                    v-for="item in majorList"
                    :key="item.id"
                    :label="item.majorName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" placeholder="请选择性别" :disabled="title == '分配班级'">
                  <el-option
                    v-for="dict in dict.type.sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入手机号" type="tel" :disabled="title == '分配班级'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-input v-model="form.nation" placeholder="请选择民族" :disabled="title == '分配班级'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学生类型" prop="studentType">
                <el-select v-model="form.studentType" placeholder="请选择学生类型" :disabled="title == '分配班级'">
                  <el-option
                    v-for="dict in dict.type.student_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="招生状态" prop="zsStatus">
                <el-select v-model="form.zsStatus" placeholder="请选择招生状态" :disabled="title == '分配班级'">
                  <el-option
                    v-for="dict in dict.type.student_zsstatus"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="招生年份" prop="zsYear">
                <el-date-picker v-model="form.zsYear" value-format="yyyy"  type="year" placeholder="选择招生年份" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="title == '分配班级'">
              <el-form-item label="分配班级" prop="clazzId">
                <el-select v-model="form.clazzId" placeholder="请选择班级">
                  <el-option
                    v-for="item in clazzList"
                    :key="item.id"
                    :label="item.clazzName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { deptList, majorList, clazzList } from "@/api/student";
  import { enrollList, addEnroll, updateEnroll, delEnroll, getEnroll, assignClazz } from "@/api/enroll";
  import Crontab from '@/components/Crontab'
  import { getToken } from "@/utils/auth";
  export default {
    dicts: ['sys_user_sex','student_type','student_zsstatus'],
    name: "Student",
    components: { Crontab },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 定时学生信息表格数据
        dataList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          studentName: undefined,
          deptId: undefined,
          majorId: undefined,
          zsYear: null,
        },
        // 表单参数
        form: {
            candidateNumber:undefined,
            studentName:undefined,
            deptId:undefined,
            majorId:undefined,
            sex:undefined,
            phone:undefined,
            nation:undefined,
            studentType:undefined,
            idCard: undefined,
            zsStatus: null,
            zsYear: null,
        },
        majorList:[],
        deptList:[],
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/enroll/importData"
        },
        clazzList:[],
      };
    },
    computed: {
      // 表单校验
      rules() {
        const base = {
          candidateNumber: [
             { required: true, message: "准考证号不能为空", trigger: "blur" }
           ],
           studentName: [
             { required: true, message: "姓名不能为空", trigger: "blur" }
           ],
           deptId: [
             { required: true, message: "系部不能为空", trigger: "blur" }
           ],
           majorId: [
             { required: true, message: "专业不能为空", trigger: "blur" }
           ],
           sex: [
             { required: true, message: "性别不能为空", trigger: "blur" }
           ],
           phone: [
             { required: true, message: "手机号不能为空", trigger: "blur" }
           ],
           nation: [
             { required: true, message: "民族不能为空", trigger: "blur" }
           ],
           studentType: [
             { required: true, message: "学生类型不能为空", trigger: "blur" }
           ],
           idCard: [
             { required: true, message: "身份证号不能为空", trigger: "blur" },
             { min: 18, max: 18, message: '身份证号长度为18位', trigger: 'blur' },
             { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
           ],
           zsStatus: [
             { required: true, message: "招生状态不能为空", trigger: "blur" }
           ],
           zsYear: [
             { required: true, message: "招生年份不能为空", trigger: "blur" }
           ],
        };
        // 仅在“分配班级”场景下才加 clazzId 的必填规则
        if (this.title === '分配班级') {
          base.clazzId = [
            { required: true, message: '请选择班级', trigger: 'change' }
          ];
        }

        return base;
      }
    },
    watch: {
      title() {
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate(); // 清除旧错误提示
        });
      }
    },
    created() {
      this.getList();
      this.getSelectList()
    },
    methods: {
      /** 查询定时学生信息列表 */
      getList() {
        this.loading = true;
        enrollList(this.queryParams).then(res => {
          this.dataList = []
          this.dataList = res.rows;
          this.total = res.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          studentName: undefined,
          deptId: undefined,
          majorId: undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加学生信息";
      },
      /** 修改/分配信息按钮操作 */
      handleUpdate(row,i) {
        this.reset();
        const id = row.id || this.ids;
        getEnroll(id).then(response => {
          this.form = response.data;
          this.form.studentType = String(response.data.studentType)
          this.form.zsStatus = String(response.data.zsStatus)
          this.open = true;
          this.title = !!i ? '分配班级' : "修改学生信息";
        });
        // 获取课程下拉接口
        clazzList().then(res=>{
          this.clazzList = res
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              if(this.title === '分配班级'){
                assignClazz(this.form).then(response => {
                  this.$modal.msgSuccess("分配成功");
                  this.open = false;
                  this.getList();
                });
              }else{
                updateEnroll(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              }        
            } else {
              addEnroll(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(function() {
          return delEnroll(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      // 获取下拉接口
      getSelectList(){
        // 获取系部下拉接口
        deptList().then(res=>{
          this.deptList = res.data
        })
        // 获取专业下拉接口
        majorList().then(res=>{
          this.majorList = res
        })
      },
       /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "录取学生信息导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('system/enroll/importTemplate', {}, `录取学生信息表${new Date().getTime()}.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList){
        this.upload.isUploading = true;
      },
      handleFileSuccess(response, file, fileList){
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/enroll/export', {
          ...this.queryParams
        }, `学生${new Date().getTime()}.xlsx`)
      },
      // 列表学生类型回显
      formatInnerStudentTypeName(row){
        let name = ''
        this.dict.type.student_type.forEach(j=>{
          if(row.studentType == Number(j.value)){
              name = j.label
            }
        })
        return name
      },
      // 列表状态回显
      formatInnerZsStatus(row){
        let name = ''
        this.dict.type.student_zsstatus.forEach(j=>{
          if(row.zsStatus == Number(j.value)){
              name = j.label
            }
        })
        return name
      },
    }
  };
</script>

<style>
  .enrollPage .el-form .el-input--medium .el-input__inner,.enrollPage .el-dialog .el-input--medium .el-input__inner{
    width: 260px;
  }
</style>